package fi.vamk.android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class menu extends Activity implements View.OnClickListener {
	//setting IP address http://www.schooltwo.com/vaasa/vaasa/
	//public  static String IpAddress = "http://www.schooltwo.com/vaasa/vaasa/";
	public  static String IpAddress = "http://192.168.9.1/vaasa/";
	Button login;
	private EditText username;
	private EditText password;
	public static Integer userId;
	public static String name;
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        login=(Button)findViewById(R.id.login);
        username=(EditText)findViewById(R.id.username);
        password=(EditText)findViewById(R.id.password);
        login.setOnClickListener(this);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.menu_button1, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.exit:
        	finish();
            return true;
        case R.id.signup:
        	startActivity(new Intent(menu.this, register.class));
         	finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    public void onClick(View view) {
	    	if (view == login)
	    	{
	    		String strUsername = username.getEditableText().toString();
	    		String strPassword = password.getEditableText().toString();
	    		name = username.getEditableText().toString();
            	postLoginData( strUsername, strPassword);
	    	}
    	}
    public void alertOkOnly(String title, String message)
    {
    	AlertDialog.Builder builder=
        	new AlertDialog.Builder(menu.this);
        	builder
        	.setTitle(title)
        	.setMessage(message)
        	.setPositiveButton("OK", null)
        	.show();
    }
    public void postLoginData( String username, String Password) {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(IpAddress + "login.php");
        //HttpPost httppost = new HttpPost("http://www.google.com");
        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", Password));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            InputStream inputStream = response.getEntity().getContent();

            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            StringBuilder stringBuilder = new StringBuilder();

            String bufferedStrChunk = null;

            while((bufferedStrChunk = bufferedReader.readLine()) != null){
                stringBuilder.append(bufferedStrChunk);
            }
            if(Integer.parseInt(stringBuilder.toString()) > 0 ){
            	userId = Integer.parseInt(stringBuilder.toString());
            	startActivity(new Intent(menu.this, menuList.class));
	         	finish();
            	//setContentView(R.layout.menu);
            }else{
            	alertOkOnly("Authentication Failed!", "Invalid username and password, please supply correct information and try again"  );
            }
            
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        	alertOkOnly("Exception!", e.toString()  );
        } catch (IOException e) {
            // TODO Auto-generated catch block
        	alertOkOnly("Exception!", e.toString()  );
        }
    } 
    }
